#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
天翼云盘分享数据库管理模块
"""

import sys
import os
from typing import Dict, List, Any, Optional
from datetime import datetime

# 添加项目根目录到路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from src.common.database import get_engine, get_database_config
from src.common.unified_logging import get_logger

# 数据库配置
DB_CONFIG = get_database_config()
logger = get_logger(__name__)

# 使用公共数据库引擎
engine = get_engine()


class ShareDatabaseManager:
    """天翼云盘分享数据库管理器"""
    
    def __init__(self):
        self.engine = engine
        self.logger = logger
    
    def create_tables(self):
        """创建分享相关数据表"""
        tables = {
            'tianyi_shares': """
                CREATE TABLE IF NOT EXISTS tianyi_shares (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    share_code VARCHAR(50) UNIQUE NOT NULL,
                    share_name VARCHAR(255),
                    share_user VARCHAR(100),
                    share_time DATETIME,
                    access_code VARCHAR(50),
                    file_count INT DEFAULT 0,
                    total_size BIGINT DEFAULT 0,
                    status ENUM('active', 'expired', 'deleted') DEFAULT 'active',
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    INDEX idx_share_code (share_code),
                    INDEX idx_status (status),
                    INDEX idx_created_at (created_at)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
            """,
            'tianyi_files': """
                CREATE TABLE IF NOT EXISTS tianyi_files (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    share_id INT,
                    file_id VARCHAR(100),
                    file_name VARCHAR(255) NOT NULL,
                    file_path VARCHAR(1000),
                    file_size BIGINT DEFAULT 0,
                    file_type ENUM('file', 'folder') DEFAULT 'file',
                    mime_type VARCHAR(100),
                    parent_id VARCHAR(100),
                    download_url TEXT,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    FOREIGN KEY (share_id) REFERENCES tianyi_shares(id) ON DELETE CASCADE,
                    INDEX idx_share_id (share_id),
                    INDEX idx_file_id (file_id),
                    INDEX idx_parent_id (parent_id),
                    INDEX idx_file_type (file_type)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
            """,
            'tianyi_access_log': """
                CREATE TABLE IF NOT EXISTS tianyi_access_log (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    share_code VARCHAR(50),
                    access_ip VARCHAR(45),
                    user_agent TEXT,
                    access_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    action VARCHAR(50),
                    file_path VARCHAR(1000),
                    status VARCHAR(20),
                    INDEX idx_share_code (share_code),
                    INDEX idx_access_time (access_time),
                    INDEX idx_access_ip (access_ip)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
            """
        }
        
        return self.db.create_tables(tables)
    
    def insert_share(self, share_code: str, share_name: str = '', share_user: str = '',
                    access_code: str = '', file_count: int = 0, total_size: int = 0) -> bool:
        """插入分享记录"""
        sql = """
        INSERT INTO tianyi_shares 
        (share_code, share_name, share_user, access_code, file_count, total_size)
        VALUES (%s, %s, %s, %s, %s, %s)
        ON DUPLICATE KEY UPDATE
        share_name = VALUES(share_name),
        share_user = VALUES(share_user),
        access_code = VALUES(access_code),
        file_count = VALUES(file_count),
        total_size = VALUES(total_size),
        updated_at = CURRENT_TIMESTAMP
        """
        
        return self.db.execute_query(sql, (share_code, share_name, share_user, 
                                         access_code, file_count, total_size))
    
    def get_share(self, share_code: str) -> Optional[Dict]:
        """获取分享记录"""
        sql = "SELECT * FROM tianyi_shares WHERE share_code = %s"
        result = self.db.fetch_one(sql, (share_code,))
        return result
    
    def insert_file(self, share_id: int, file_data: Dict[str, Any]) -> bool:
        """插入文件记录"""
        sql = """
        INSERT INTO tianyi_files 
        (share_id, file_id, file_name, file_path, file_size, file_type, 
         mime_type, parent_id, download_url)
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
        """
        
        params = (
            share_id,
            file_data.get('file_id', ''),
            file_data.get('file_name', ''),
            file_data.get('file_path', ''),
            file_data.get('file_size', 0),
            file_data.get('file_type', 'file'),
            file_data.get('mime_type', ''),
            file_data.get('parent_id', ''),
            file_data.get('download_url', '')
        )
        
        return self.db.execute_query(sql, params)
    
    def log_access(self, share_code: str, access_ip: str, user_agent: str,
                  action: str, file_path: str = '', status: str = 'success') -> bool:
        """记录访问日志"""
        sql = """
        INSERT INTO tianyi_access_log 
        (share_code, access_ip, user_agent, action, file_path, status)
        VALUES (%s, %s, %s, %s, %s, %s)
        """
        
        return self.db.execute_query(sql, (share_code, access_ip, user_agent,
                                         action, file_path, status))


def init_database():
    """初始化数据库"""
    share_db = ShareDatabaseManager()
    if share_db.create_tables():
        logger.info("天翼云盘分享数据库初始化成功")
        return share_db
    else:
        logger.error("天翼云盘分享数据库初始化失败")
        return None


if __name__ == "__main__":
    # 测试数据库连接和初始化
    share_db = init_database()
    if share_db:
        print("数据库测试完成")